package csloader.loaders
{
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import csloader.requests.SimpleRequest;
	import csloader.util.KeyValuePair;
	import csloader.util.RequestMethod;
	
	public class TextLoaderBase extends SimpleRequest implements ILoader
	{
		protected var responseEncoding:String = null;	//默认不使用编码转换规则	utf-8
		
		public function TextLoaderBase(callback:Function)
		{
			super(callback);
		}
		
		
		/**
		 * 准备请求
		 * @param url 链接地址
		 * @param parms 请求参数
		 * @param requestMethod 提交方式
		 * @param args 响应内容的编码，可选值为utf-8、gbk、gb2312
		 * @return 
		 * 
		 */
		override public function getRequest(url:String, parms:KeyValuePair=null, requestMethod:String=RequestMethod.Get, ...args) : URLRequest
		{
			if(args[0])
				responseEncoding = args[0].toString();
			
			return super.getRequest(url, parms, requestMethod, args);
		}
		
		/**
		 * 对响应数据进行转换编码
		 * @param url
		 * @param response
		 * 
		 */
		override public function sendResponse(url:String, response:*=null) : void
		{
			if(typeof(response) != "object" && responseEncoding)
			{
				var BA:ByteArray = new ByteArray();
				BA.writeBytes(response);
				BA.position = 0;
				response = BA.readMultiByte(BA.length, responseEncoding);
			}
			super.sendResponse(url, response);
		}
		
		public function call(url:String, parms:KeyValuePair=null, requestMethod:String=RequestMethod.Get, ...args):void
		{
			sendRequest(getRequest(url, parms, requestMethod, args));
		}
	}
}